#include <boost/asio.hpp>
#include <iostream>
#include <unordered_map>
#include <string>
#include<map>
using boost::asio::ip::tcp;
 
// 客户端信息结构体
struct ClientInfo {
    std::string ip;
    unsigned short port;
    std::string username;
    std::string udpPort;
};

//定义一个map来存储客户端信息
std::map<int,struct ClientInfo> maps;

// 信令服务器类
class SignalingServer {
public:
    SignalingServer(boost::asio::io_context& io_context, unsigned short port)
        : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) {
        start_accept();
    }

private:
    // 开始接受客户端连接
    void start_accept() {
        auto socket = std::make_shared<tcp::socket>(acceptor_.get_executor());
        acceptor_.async_accept(*socket, [this, socket](const boost::system::error_code& ec) {
            if (!ec) {
                // 获取客户端信息
                auto endpoint = socket->remote_endpoint();
                std::string client_ip = endpoint.address().to_string();
                unsigned short client_port = endpoint.port();
                
                std::cout << "New client connected: " << client_ip << ":" << client_port << std::endl;
            
                // 保存客户端信息
                clients_[socket] = {client_ip, client_port,"",""};


                // 处理客户端
                handle_client(socket);
            }
            start_accept(); // 继续接受新连接
        });
    }

    // 处理客户端
    void handle_client(std::shared_ptr<tcp::socket> socket) {
        auto buffer = std::make_shared<std::array<char, 1024>>();
        socket->async_read_some(boost::asio::buffer(*buffer), 
        [this, socket, buffer](const boost::system::error_code& ec, std::size_t length) {
            if (!ec) {
                bool isCunzai = false;
                std::string message(buffer->data(), length);
                std::cout << "Received message: " << message << std::endl;
                //判断是不是第一次发特征，如果是第一次话就记录

                if(clients_[socket].username==""||clients_[socket].udpPort==""){
                    if(clients_[socket].username=="")
                    {
                    clients_[socket].username=message;
                    }else if(clients_[socket].udpPort==""){
                        clients_[socket].udpPort=message;
                    }
                }else{
                    //不是的话，就找到该特征值，将该特真值发生给该特征值对应的客户端
                    for (const auto& client : clients_) {
                        if(client.second.username==message){
                            isCunzai = true;
                            boost::asio::write(*socket, boost::asio::buffer(client.second.ip + ":" + client.second.udpPort+":"+client.second.username));
                            boost::asio::write(*client.first, boost::asio::buffer(clients_[socket].ip + ":" + clients_[socket].udpPort+":"+clients_[socket].username));
                        }

                    }
                      //如果不存在该用户的特征值，就返回no
                if(isCunzai==false){
                    boost::asio::write(*socket, boost::asio::buffer("no"));

                }else{
                    isCunzai = false;
                }

                }
              
                // 继续读取
                handle_client(socket);
            } else {
                // 客户端断开连接
                std::cout << "Client disconnected: " << clients_[socket].ip << ":" << clients_[socket].port << std::endl;
                clients_.erase(socket);
            }
            


        });
    }

    tcp::acceptor acceptor_;
    std::unordered_map<std::shared_ptr<tcp::socket>, ClientInfo> clients_;
};

int main() {
    try {
        boost::asio::io_context io_context;
        SignalingServer server(io_context, 12345); // 监听端口 12345
        std::cout << "Signaling server started on port 12345" << std::endl;
        io_context.run();
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}